package com.maybach.web.controller;

import com.maybach.core.ao.LoginAO;
import com.maybach.core.form.LoginForm;
import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.WebUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Controller
@RequestMapping("/")
public class LoginController {
    @Autowired
    protected LoginAO loginAO;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 登陆页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "login")
    public String login(@RequestParam(required = false, value = "redirectUrl") String redirectUrl, ModelMap model) {
        model.addAttribute("redirectUrl", redirectUrl);
        if (!model.containsAttribute("loginForm")) {
            LoginForm loginForm = new LoginForm();
            model.addAttribute(loginForm);
        }
        return "login";
    }

    /**
     * 登陆操作
     *
     * @return
     */
    @RequestMapping(value = "doLogin", method = RequestMethod.POST)
    public String doLogin(@Valid LoginForm loginForm, BindingResult bindingResult, @RequestParam(required = false, value = "redirectUrl") String redirectUrl, RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(loginForm.getName(), loginForm.getPassword()));
        } catch (Exception e) {
            logger.error("登陆失败[userName=" + loginForm.getName() + "]", e);
            bindingResult.addError(new FieldError("loginForm", "password", "密码错误"));
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }

        return WebConstants.REDIRECT_PREFIX+"center";
    }


    /**
     * 登出操作操作
     *
     * @return
     */
    @RequestMapping("logout")
    public String logout(ModelMap model) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() || subject.isRemembered()) {
            subject.logout();
        }
        return "forward:login";
    }

    /**
     * 首页
     * @param model
     * @return
     */
    @RequiresAuthentication
    @RequestMapping( value ={"center", ""})
    public String center(ModelMap model) {
        return "center";
    }

}